package cn.sinonet.sms.dao.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.sinonet.sms.dao.SmsDao;
import cn.sinonet.sms.dwr.SmsBean;

@Repository("smsDao")
public class SmsDaoJpa implements SmsDao {

	protected final Log log = LogFactory.getLog(getClass());

	public static final String PERSISTENCE_UNIT_NAME = "ApplicationEntityManager";

	@PersistenceContext(unitName = PERSISTENCE_UNIT_NAME)
	private EntityManager entityManager;

	@Autowired
	private DataSource dataSource;

	public EntityManager getEntityManager() {
		return this.entityManager;
	}

	/**
	 * Constructor that sets the entity to User.class.
	 */
	public SmsDaoJpa() {
	}

	@Override
	public List<SmsBean> getSmsList(String hql, int offset, int length)
			throws Exception {

		Query query = getEntityManager().createNativeQuery(hql);
		// Query query = getEntityManager().createQuery(hql);
		query.setFirstResult(offset);
		query.setMaxResults(length);

		List<Object> resultList = query.getResultList();

		List<SmsBean> list = new ArrayList<SmsBean>();

		for (int i = 0; i < resultList.size(); i++) {

			// createdTime , message , name , phoneNumber , state
			Object[] o = (Object[]) resultList.get(i);

			SmsBean smsBean = new SmsBean((String) o[3], (String) o[1],
					(String) o[2], (String) o[4], (String) o[0]);

			smsBean.setId(Long.valueOf(i));

			list.add(smsBean);

		}

		return list;
	}

	@Override
	public int getSmsCount(String hql) throws Exception {

		Query query = getEntityManager().createNativeQuery(hql);

		List resultList = query.getResultList();

		java.math.BigInteger o = (java.math.BigInteger) resultList.get(0);

		return o.intValue();

	}

}
